package com.epam.DAO.impl;

import javax.ejb.Stateless;
import javax.enterprise.inject.Produces;
import javax.faces.context.FacesContext;
import javax.interceptor.Interceptors;
import javax.persistence.TypedQuery;
import javax.servlet.http.HttpServletRequest;

import com.epam.DAO.ClientDAO;
import com.epam.entity.Client;
import com.epam.utils.Interceptor;
import com.epam.utils.LoggedClient;

@Interceptors(Interceptor.class)
@Stateless
public class ClientDAOImpl extends GenericDAOImpl<Client> implements ClientDAO {

	public ClientDAOImpl() {
		super(Client.class);
	}

	@Produces @LoggedClient
	@Override
	public Client read() {

		Client client = null;

		try {
			String login = ((HttpServletRequest) FacesContext
					.getCurrentInstance().getExternalContext().getRequest())
					.getUserPrincipal().toString();

			TypedQuery<Client> query = em.createQuery(
					"SELECT c FROM Client c WHERE c.user.login = :login",
					Client.class);
			query.setParameter("login", login);
			client = query.getResultList().get(0);
		} catch (Exception e) {
			logger.debug(e.toString());
		}

		return client;
	}

}
